package dao.Implementation;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import Donnees.Periode;
import Util.HibernateUtil;
import dao.Interfaces.IPeriodeDAO;

public class PeriodeDAO implements IPeriodeDAO {
	public PeriodeDAO() {
	}

	public List<Periode> selectAll() {
		List<Periode> listePeriode = new ArrayList<Periode>();

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		listePeriode.addAll(session.createQuery("from Periode").list());

		session.flush();
		tx.commit();
		session.close();

		return listePeriode;
	}

	public long insert(Periode p) {
		Periode periodeTemp = p;
		Long msgId;

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		msgId = (Long) session.save(periodeTemp);

		session.flush();
		tx.commit();
		session.close();
		
		return msgId;
	}
	
	public int delete(Periode p) {
		Periode periodeTemp = p;
		int retour;
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();
		
		retour = session.createQuery("delete from Periode where nom='" + periodeTemp.getNom() + "'").executeUpdate();

		session.flush();
		tx.commit();
		session.close();
		
		return retour;
	}
	
	public Periode getById(long id) {
		Periode periodeTemp = new Periode();

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		periodeTemp = (Periode) session.createQuery("from Periode where id='" + id + "'").list().get(0);

		session.flush();
		tx.commit();
		session.close();

		return periodeTemp;
	}
}
